package com.lp;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class IOTest {
    public static void main(String[] args) throws Exception{
        String sourcePath = "D:\\安装下载\\软件安装包\\操作系统\\Linux\\CentOS\\CentOS-8.1.1911-x86_64-dvd1.iso";
        //"D:\\办公文件\\项目资料\\地震数据管理平台\\样本数据\\实际采样\\Gulf178_su2starttime_omega.segy"
        String targetPath = "D:\\test\\a";
        long l1 = System.currentTimeMillis();
//        readByIO(sourcePath,targetPath);
        readByNio(sourcePath,targetPath);
        long l2 = System.currentTimeMillis();
        System.out.println(l2-l1);
    }

    public static void readByIO(String sourcePath, String targetPath) throws Exception{
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(sourcePath)));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(targetPath)));
        byte[] temp = new byte[1024];
        int size = 0;
        while((size = bis.read(temp)) != -1){
            bos.write(temp, 0,size);
        }
        bis.close();
    }

    public static void readByNio(String sourcePath, String targetPath) throws Exception{
        FileInputStream fis = new FileInputStream(new File(sourcePath));
        FileOutputStream fos = new FileOutputStream(new File(targetPath));
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        FileChannel readChannel = fis.getChannel();
        readChannel.read(byteBuffer);
        FileChannel wrtiteChannel = fos.getChannel();
        while(true){
            byteBuffer.clear();
            int r = readChannel.read(byteBuffer);
            if(r == -1){
                break;
            }
            byteBuffer.flip();
            wrtiteChannel.write(byteBuffer);
        }
    }
}
